import config from './config'
const md5 = require('md5')
const $ = {
	log: console.log,
	error: console.error,
	warn: console.warn,
	showModal(str, suc = $.noop) {
		return uni.showModal({
			content: str,
			success(res) {
				if (res.confirm) {
					suc()
				}
			}
		})
	},
	showModalA(str, suc = $.noop) {
		return uni.showModal({
			content: str,
			showCancel: false,
			success(res) {
				if (res.confirm) {
					suc()
				}
			}
		})
	},
	//改变数据结构
	change(res) {
		let list = []
		let key1 = Object.keys(res)[0]
		if (Array.isArray(res[key1])) {
			res[key1].forEach((ele, ind) => {
				let item = {}
				for (let i in res) {
					item[i] = res[i][ind]
					if (typeof res[i] == 'string') {
						item[i] = res[i]
					}
				}
				list.push(item)
			})
		}

		return list
	},
	md5: md5,
	noop: () => {},
	isRefresh: false,
	imgSrc: config.imgSrc,
	ajaxUrl: config.ajaxUrl,
	domain: config.domain,
	rootDomain: config.rootDomain,
	winWidth: uni.getSystemInfoSync().windowWidth,
	winHeight: uni.getSystemInfoSync().windowHeight,
	appid: wx.getAccountInfoSync().miniProgram.appId,
	shopping(str) {
		return 'Shopping.php?action=' + str + '&appid=' + this.appid;
	},
	user(str) {
		return 'User.php?action=' + str + '&appid=' + this.appid;
	},
	index(str) {
		return 'Index.php?action=' + str + '&appid=' + this.appid;
	},
	product(str) {
		return 'Product.php?action=' + str + '&appid=' + this.appid;
	},
	$bg(str, width, height) {
		return `background:url(${config.imgSrc}${str}?v=${config.picRand}) no-repeat center center; background-size:${width}rpx ${height}rpx; width:${width}rpx; height:${height}rpx;`
	},
	auth_token() {
		let id = $.getLocal('userId')
		let safeCode = $.getLocal('safeCode')
		// $.log(id, safeCode)
		return md5(id + '+' + safeCode)
	},
	$img(str) {
		return `${config.imgSrc}${str}?v=${config.picRand}`
	},
	go(url) {
		let newUrl = '/pages/' + url + ''
		if (url.includes('?')) {
			newUrl = '/pages/' + url.split('?')[0] + '?' + url.split('?')[1]
		}
		uni.navigateTo({
			url: newUrl
		})
	},
	$go(url) {
		let newUrl = '/pages/' + url + ''
		if (url.includes('?')) {
			newUrl = '/pages/' + url.split('?')[0] + '?' + url.split('?')[1]
		}
		uni.navigateTo({
			url: newUrl
		})
	},
	$goSelf(url) {
		let newUrl = '/pages/' + url + ''
		if (url.includes('?')) {
			newUrl = '/pages/' + url.split('?')[0] + '?' + url.split('?')[1]
		}
		uni.redirectTo({
			url: newUrl
		})
	},
	call(phoneNumber = "18888888888") {
		uni.makePhoneCall({
			phoneNumber,
			success: function() {
				console.log("拨打电话成功！");
			},
			fail: function() {
				console.log("拨打电话失败！");
			},
		});
	},
	login(back = $.noop) {
		let loginSuccess = (code) => {
			let url = 'User.php?action=getInfo' + '&appid=' + this.appid;
			let userInfo = $.getLocal('userInfo')
			$.log('local-userInfo：', userInfo)

			$.log(code)


			if (!userInfo) {
				userInfo = {
					nickName: '微信用户',
					avatarUrl: '',
					gender: ''
				}
			}
			let data = {
				code: code,
				nickname: userInfo.nickName,
				headimgurl: userInfo.avatarUrl,
				sex: userInfo.gender
			}

			//推荐人
			if ($.getLocal('tuijianren')) {
				data.user_id = $.getLocal('tuijianren')
			}

			$.setLocal('nickname', userInfo.nickName)
			$.setLocal('headimgurl', userInfo.avatarUrl)
			$.showLoading()
			//if (!$.getLocal('userId')) {
				$.np(url, data).then(
					res => {
						$.hideLoading()
						$.log('登录成功', res)
						$.log('登录成功', res)
						$.log('登录成功', res)
						$.log('登录成功', res.Id)
						try{
							$.setLocal('userId', res.Id)
						}catch(e){
							$.log(e.message)
						}
						$.setLocal('safeCode', res.safe_code)
						$.setLocal('openid', res.openid)
						$.setLocal('session_key', res.session_key)
						//如果type=5
						if ($.getLocal('tuijianrenType') == '5' && res.is_exist == 1) {
							let url = 'Index.php?action=getBusunessInto'
							let data = {
								user_id: res.Id
							}
							$.np(url, data).then(res => {
								$.log(res)
							})
						}

						back()
					}
				)
			// } else {
			// 	$.hideLoading()
			// }
		}


		uni.checkSession({
			success() {
				if (!$.getLocal('userId')) {
					$.log('没有userId')
					uni.login({
						success(res) {
							if (res.code) {
								loginSuccess(res.code)
							} else {
								$.tip('登陆失败，请重试')
								$.log('登录失败！' + res.errMsg)
							}
						}
					})
				} else {
					back()
				}
			},
			fail() {
				$.setLocal('isLogin', false)
				$.log('未登录')
				uni.login({
					success(res) {
						if (res.code) {
							loginSuccess(res.code)
						} else {
							$.tip('登陆失败，请重试')
							$.log('登录失败！' + res.errMsg)
						}

					}
				})
			}
		})

	},
	goSelf(url) {
		uni.redirectTo({
			url: url
		})
	},
	back(num) {
		if (num == undefined) {
			num = 1
		}
		uni.navigateBack({
			delta: num
		})
	},
	reLaunch(str) {
		uni.reLaunch({
			url: str
		})
	},
	removeLocal: uni.removeStorageSync,
	setLocal: uni.setStorageSync,
	getLocal: uni.getStorageSync,
	clearLocal: uni.clearStorageSync,
	goBottom() {
		setTimeout(() => {
			uni.pageScrollTo({
				scrollTop: 100000,
				duration: 300
			})
		}, 500)
	},
	isIphone() {
		let phoneModel = uni.getSystemInfoSync().model
		if (phoneModel.indexOf('iPhone') !== -1 || phoneModel.indexOf('iphone') !== -1) {
			return true
		}
		return false
	},
	isIphoneX() {
		let phoneModel = uni.getSystemInfoSync().model
		if (phoneModel.indexOf('iPhone X') !== -1 || phoneModel.indexOf('iPhone XR') !== -1 || phoneModel.indexOf(
				'iPhone XS') !== -1) {
			return true
		}
		if (phoneModel.indexOf('iPhone X') !== -1 || phoneModel.indexOf('iPhone Xr') !== -1 || phoneModel.indexOf(
				'iPhone Xs') !== -1) {
			return true
		}

		return false
	},
	async ajax(url, data = {}, method = 'post') {
		if ((!url.includes('https:')) && (!url.includes('http:'))) {
			let base = $.ajaxUrl
			//浏览器平台-使用代理
			// #ifdef  H5
			if (process.env.NODE_ENV === 'development') {
				base = '/api/'
			}

			// #endif
			url = base + url
		}

		let uniRes = await uni.request({
			url: url,
			data: data,
			header: {
				'content-type': 'application/x-www-form-urlencoded'
			},
			method: method
		})

		let [err, res] = uniRes;

		let newRes = {
			isError: true
		}
		if (url.includes('wxpay.php')) {
			return res.data
		}
		$.log(res)
		if(typeof(res.data)=='string'){
			//不知道为什么phpjsonencode会有bom，trim掉
			res.data = JSON.parse(res.data.trim());
		}
		let restemp = res.data
		$.log(restemp)
		if (restemp.code == 0) {
			if (restemp.data == null) {
				newRes = {}
			} else {
				newRes = restemp.data
			}

		} else {
			$.error('error', '----', restemp.code, restemp.msg)
			if (!url.includes('applyStatus')) {
				$.tip(restemp.msg)
			}

			newRes.code = restemp.code
			newRes.msg = restemp.msg
			newRes.res = restemp.data

		}
		$.log(newRes)
		return newRes
	},
	async np(url, data = {}) {
		let common = {
			user_id: $.getLocal('userId'),
			auth_token: $.auth_token()
		}
		data = Object.assign(common, data)
		return await $.ajax(url, data, 'post')
	},
	async get(url, data = {}) {
		return await $.ajax(url, data, 'get')
	},
	isPhone(str) {
		var phone_val = str;
		var reg = /^1[1|2|3|4|5|6|7|8|9]\d{9}$/;
		if (reg.test(phone_val)) {
			return true;
		} else {
			return false;
		}
	},
	tip(str) {
		uni.showToast({
			title: str,
			icon: "none"
		})
	},
	suc(str) {
		uni.showToast({
			title: str,
			icon: "success"
		})
	},
	showLoading(str = '请稍候') {
		uni.showLoading({
			title: str,
			mask: true
		})
	},
	hideLoading() {
		uni.hideLoading()
	},
	//判断字符串是否为json
	isJSON(str) {
		if (typeof str == 'string') {
			try {
				var obj = JSON.parse(str);
				if (typeof obj == 'object' && obj) {
					return true;
				} else {
					return false;
				}

			} catch (e) {
				$.log('error：' + str + '!!!' + e);
				return false;
			}
		}
		return false
	},


}



$.getUsInfo = () => {
	let url = $.user('userInfo')
	return $.post(url).then(res => {
		if (res.isError) {
			return
		}
		return res
	})
}

$.formatImg = function(html) {
	var newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
		var match = match.replace(/style=\"(.*)\"/gi, 'style="max-width:100%;"');
		return match;
	});
	return newContent;
}

$.deepCopy = (obj) => {
	// 判断是否是对象
	if (typeof obj !== 'object') return;
	// 判断obj类型，根据类型新建一个对象或者数组
	var newObj = obj instanceof Array ? [] : {}
	// 遍历对象，进行赋值
	for (var key in obj) {
		if (obj.hasOwnProperty(key)) {
			let val = obj[key];
			// 判断属性值的类型，如果是对象，递归调用deepCopy
			newObj[key] = typeof val === 'object' ? $.deepCopy(val) : val
		}
	}
	return newObj
}



$.post = $.np

export default $